var cheerio = require('cheerio');
var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;
var mysqlProxy = require('./config').mysqlProxy;

function run() {
    var ipList = [];
    var ipIndex = 0;

    function getIpList() {
        var connection = mysql.createConnection(mysqlProxy);
        var queryString = 'select * from ip_table1 where success_count>5 ' +
            'order by success_count desc limit 1000 ';
        connection.connect();
        connection.query(queryString, function (err, res) {
            if (err) {
                console.log(err);
                console.log();

            } else {
                ipList = res;
                for (var i = 0; i < 50; i++) {
                    main(i);
                }
            }
        });
        connection.end();
    }
    getIpList();
    function main(offset) {
        var ipItem;
        var retryCount = 0;

        function getIpItem() {
            ipItem = ipList[ipIndex];
            if (ipItem.using) {
                ipIndex += 1;
                getIpItem();
            } else {
                ipItem.using = true;


                console.log(ipItem);
                console.log();

            }
        }
        getIpItem();

        function changeIpItem() {
            ipItem.using = false;
            if (ipIndex < ipList.length - 1) {
                ipIndex += 1;

            } else {
                ipIndex = 0;
            }
            console.log('ipIndex');
            console.log(ipIndex);
            console.log();

            getIpItem();
        }

        function getProxy(item) {
            var ip = item.ip;
            var port = item.port;
            return `http://${ip}:${port}`;
        }

        var album;
        function getAlbum() {
            var connection2 = mysql.createConnection(mysqlCloudMusic);
            var query2 = `select * from album where (ISNULL( song_updated )) limit 1 offset ${offset}`;

            connection2.query(query2, function (err, res) {
                if (err) {
                    console.log(err);

                } else {
                    console.log(res);
                    console.log();

                    if (res.length === 0) {
                        console.log('no album');
                        // setTimeout(function () {
                        //     getAlbum();
                        // }, 600 * 1000);
                    } else {
                        album = res[0];

                        getSong();
                    }
                }
            });
            connection2.end();
        }
        getAlbum();

        var songList = [];
        function getSong() {
            const albumId = album.id;
            const artistId = album.artist_id;

            var proxy = getProxy(ipItem);

            var url = `https://music.163.com/album?id=${albumId}`;
            superagent.get(url)
                .timeout(10000)
                .proxy(proxy)
                .end(function (err2, res2) {
                    console.log(url);
                    console.log('ipIndex');
                    console.log(ipIndex);
                    console.log(proxy);
                    console.log();

                    if (err2) {
                        console.log('http err');
                        console.log(url);
                        if (retryCount < 3) {
                            retryCount += 1;
                            getSong();
                        } else {
                            retryCount = 0;
                            changeIpItem();
                            getSong();
                        }
                    } else {
                        console.log('http success');
                        var text = res2.text;
                        fs.writeFile('html/song.html', text, function () { });

                        fs.writeFile('html/song.html', text, function () { })

                        if (/你要查找的网页找不到/g.test(text)) {
                            console.log('你要查找的网页找不到');
                            console.log();
                            feedback();
                        } else {
                            if ((/专辑 - 网易云音乐/g).test(text)) {

                                var $ = cheerio.load(text);

                                var e1 = $('.n-songtb').eq(0);
                                var e2 = e1.find('.u-title .sub');
                                var text1 = e2.text();
                                if (text1 === '0首歌') {
                                    feedback();
                                } else {
                                    var songListElement = $('#song-list-pre-cache');
                                    if (songListElement.length > 0) {
                                        var list2 = songListElement.find('.f-hide>li');

                                        var list3 = [];
                                        list2.each((i, element) => {
                                            var item = list2.eq(i);

                                            var href = item.find('a').eq(0).attr().href;
                                            var id = Number(href.replace(/\/song\?id=/g, ''));

                                            var songName = item.text();
                                            var song = [id, songName, artistId, albumId];

                                            list3.push(song);
                                        });

                                        console.log(list3);
                                        if (list3.length > 0) {
                                            songList = list3;
                                            upload();
                                        } else {
                                            feedback();
                                        }

                                    } else {
                                        changeIpItem();
                                        getSong();
                                    }
                                }
                            } else {
                                changeIpItem();
                                getSong();
                            }

                        }



                    }
                });
        }

        function upload() {
            var connection3 = mysql.createConnection(mysqlCloudMusic);
            connection3.connect();
            var query3 = 'insert ignore into song(id,name,artist_id,album_id) values ?';
            connection3.query(query3, [songList], function (err3, res3) {
                console.log('query3 end');
                if (err3) {
                    console.log('query3 err');
                    console.log(err3);

                } else {
                    console.log('query3 success');
                    console.log(res3);
                    feedback();
                }

            });
            connection3.end();
        }


        function feedback() {
            const albumId = album.id;

            var connection4 = mysql.createConnection(mysqlCloudMusic);
            var query4 = `update album set song_updated=1 where id=${albumId}`;
            connection4.connect();
            connection4.query(query4, function (err4, res4) {
                console.log('query4 end');
                if (err4) {
                    console.log('query4 err');

                } else {
                    console.log('query4 success');
                    console.log(res4);
                    console.log('feedback end');
                    setTimeout(() => {
                        getAlbum();
                    }, 1000);
                }
            });
            connection4.end();
        }

    }
}
run();